<?php
class Controller_Admin_Home extends Controller_Template
{

	public function __construct($request, $response)
	{
		$this->template	= ('smarty:admin/home/default');
		header("Content-Type:text/html;charset=utf-8"); 

		parent::__construct($request, $response);
	}

	/**
	 * 资源位管理
	 */
	public function action_respool()
	{
		$goods_list = array();
		$respool    = new Respool();
		$flag       = $this->request->query('flag');
		$cate_list  = Kohana::config('category.sctags_resid');
		foreach($cate_list as $k => $v)
		{
			$tmp = $respool->get_res_list($v);
			$goods_list = array_merge($goods_list,$tmp);
		}

		$home   = new Homepage;
		$groups = $home->category_items();
		$position	= 'hotsale';
		$this->template->set('position',$position);
		$this->template->set('category_groups', $groups);

		$this->template->set('goods_list',$goods_list);
		$this->template->set('row',$row);
		$this->template->set('col',$col);
		$this->template->set('function_name','respool');
		$this->template->set('page_title','资源位管理');
		$this->template->set('flag',$flag);
		$this->template->set_filename('smarty:admin/resources/index');
	}

	/**
	 * 设置列表 批量保存；
	 */
	public function action_set_respool_list()
	{
		$list = array();
		$post = $this->request->post();
		$flag = false;
		foreach($post as $key => $t)
		{
			$tmp                = array();
			$exp                = explode('_',$key);
			$goods_id           = (int) $exp[1];

			if(!$goods_id)
				continue;

			if(isset($list[$goods_id]))
				continue;

			$tmp['goods_id']       = $goods_id;
			$tmp['title']          = Arr::get($post, 'title_'.$goods_id, '');;
			$tmp['position']       = Arr::get($post, 'position_'.$goods_id, '');
			$tmp['url']            = Arr::get($post, 'url_'.$goods_id, Goods::goods_detail_url($goods_id));
			$tmp['price']          = Arr::get($post, 'nowprice_'.$goods_id, '0.00');
			$tmp['img']            = Arr::get($post, 'image_'.$goods_id, '');
			$list[$goods_id]       = $tmp;
			$sort++;
		}

		$t_count = Kohana::config('respool.position.homepage.row') * Kohana::config('respool.position.homepage.column');
		if( count($list) != $t_count )
			exit;

		$respool = new Respool();
		if($respool->set_goods($list))
			$flag = true;

		header("Location:/home/respool?flag=".$flag);
		exit;
	}


	/**
	 * 缓存刷新
	 */
	public function action_refresh($cache=NULL,$param=NULL)
	{
		
		if ($cache == 'homepage')
		{
			$this->refresh_homepage();
			echo "<script>alert('刷新成功');</script>";
			echo "<script>location.href='/home/refresh';</script>";
		}

		if ($cache == 'shop')
		{
			$this->refresh_shop_template($param);
		}

		$condition = array('status' => 1);
		$shop_list = Shop::search($condition);
		$this->template->set('shop_list',$shop_list);
		$this->template->set_filename('smarty:admin/resource/refresh');
	}

	/**
	 * 删除首页缓存，刷新首页内容
	 */
	private function refresh_homepage()
	{
		return Homepage::refresh_content();
	}

	/**
	 * 删除商品页面缓存
	 */
	private function refresh_shop_template($shop_id)
	{
		if (empty($shop_id))
		{
			echo "<script>alert('刷新失败');</script>";
			echo "<script>location.href='/home/refresh';</script>";
		}
		$shop_page = Shop_View::factory('index',$shop_id);
		$shop_page->build_shop_template_cache();
		echo "<script>alert('刷新成功');</script>";
		echo "<script>location.href='/home/refresh';</script>";

	}

	/**
	 * 资源位管理ajax 获取某个商品info
	 */
	public function action_ajax_goods($goods_id)
	{
		if(Goods::invalid($goods_id))
		{
			echo "";
			exit;
		}

		$goodsres   = Goods::search(array('id'=>$goods_id));
		$goods_info = isset($goodsres['list'][$goods_id]) ? $goodsres['list'][$goods_id] : array();
		if(!empty($goods_info))
		{
			$img                             = Goods_Album::images($goods_info['goods_id'],'large');
			$goods_info['large_cover_thumb'] = isset($img[0]['img_url']) ? $img[0]['img_url'] : '';
			$goods_info['url']               = Goods::goods_detail_url($goods_info['goods_id']);
			$goods_info['nowprice']          = (float) $goods_info['promote_price'] > 0 ? $goods_info['promote_price'] : ( (float) $goods_info['min_price'] > 0 ? $goods_info['min_price'] : $goods_info['price'] );
			$goods_info['originalprice']     = $goods_info['price'];
		}

		if(empty($goods_info))
		{
			echo "";
			exit;
		}

		echo json_encode($goods_info);
	}

	public function action_index($position	= null)
	{

		$position	= strval($position);

		if(empty($position))
			$position	= 'hotsale';

		$pos_config		= Kohana::config('home.position');

		if(! in_array($position, $pos_config))
			echo '<script>alert("参数错误！");window.location.href="/home/index/";</script>';

		$html	= Home::getData($position);

		$editor_html	= editor::build('fck_html',  $html , Kohana::config('home.editor'));
		
		$this->template->set_filename('smarty:admin/home/index_editor');
		
		$this->template->set('page_title','首页促销位');
		$this->template->set('fck_html', $editor_html);
		$this->template->set('function_name', 'home');
		$this->template->set('position',$position);
		$this->response->body($this->request->render());

	}

	public function action_extension($position	= null)
	{

		$position	= strval($position);

		if(empty($position))
			$position	= 'fangchan';

		$pos_config		= Kohana::config('home.focusposition');

		if(! in_array($position, array_keys($pos_config)))
			echo '<script>alert("参数错误！");window.location.href="/home/extension";</script>';

		$html	= Home::extension_info($position);

		$editor_html	= editor::build('fck_html',  $html , Kohana::config('home.editor'));
		
		$this->template->set_filename('smarty:admin/home/extension');
		
		$this->template->set('page_title','首页促销位');
		$this->template->set('fck_html', $editor_html);
		$this->template->set('function_name', 'extension');
		$this->template->set('position',$position);
		$this->response->body($this->request->render());

	}

	/**
	 * 后台编辑json格式数据类型的数据推荐
	 * 页面字段 array(
	 *	array(
	 *   'title'     => '商品名称',
	 *   'cate_name' => '分类名称',
	 *   'img_url'   => '商品图片',
	 *   'url'       => '商品url',
	 *   'y_price'   => '商品原价',
	 *   'now_price' => '商品现价',
	 *	),
	 * )
	 */
	public function action_extension_json($position = NULL)
	{

		$position	= strval($position);

		if(empty($position))
			$position	= 'fangchan';

		$pos_config		= Kohana::config('home.focusposition');

		if(! in_array($position, array_keys($pos_config)))
			echo '<script>alert("参数错误！");window.location.href="/home/extension";</script>';

		$content	= Home::extension_info($position);

		$list = json_decode($content); 
		$goods_count = Kohana::config('home.json_count.'.$position);
		$goods_list = array();

		if(!empty($list)) {
			foreach($list as $g) {
				$goods['title']     = $g->title;
				$goods['cate_name'] = $g->cate_name;
				$goods['img_url']   = $g->img_url;
				$goods['url']       = $g->url;
				$goods['y_price']   = $g->y_price;
				$goods['now_price'] = $g->now_price;
				$goods_list[] = $goods;
			}
		}

		$list_count = count($goods_list);
		if($list_count < $goods_count) {
			for($i=$list_count;$i<$goods_count;$i++) {
				$goods['title']     = '推广标题';
				$goods['cate_name'] = '推广分类';
				$goods['img_url']   = '图片url';
				$goods['url']       = '商品链接';
				$goods['y_price']   = '原价';
				$goods['now_price'] = '现价';
				$goods_list[$i] = $goods;
			}
		}

		$this->template->set_filename('smarty:admin/home/extension');
		$this->template->set('page_title','推广数据处理');
		$this->template->set('data_format','json');
		$this->template->set('goods_list',$goods_list);
		$this->template->set('function_name', 'extension');
		$this->template->set('position',$position);
		$this->template->set('view_count',$goods_count);
	}

	/**
	 * 提交到数据库json格式保存
	 */
	public function action_insert_json()
	{
		$post_data	 = $this->request->post();
		$type   	 = Arr::get($post_data,'position');
		$action_name = Arr::get($post_data,'action_name');
		$data_counts = Kohana::config('home.json_count');
		if(!isset($data_counts[$type])) {
			echo '<script>alert("error！");window.location.href="/home/extension_json/'.$type.'"</script>';
			exit;
		}

		if($action_name == 'save')
		{
			if(in_array($type,array_keys(Kohana::config('home.focusposition'))))
			{
				$goods_list = array();
				for($i=0;$i<$data_counts[$type];$i++) {
					$goods['title']      = $post_data['title'][$i];
					$goods['cate_name']  = $post_data['cate_name'][$i];
					$goods['img_url']    = $post_data['img_url'][$i];
					$goods['url']        = $post_data['url'][$i];
					$goods['y_price']    = $post_data['y_price'][$i];
					$goods['now_price']  = $post_data['now_price'][$i];
					$goods_list[]        = $goods;
				}

				$desc = json_encode($goods_list);
				$cache_key = Kohana::config('home.cache_key.'.$type);
				if(Home::insert($desc, $type))
				{
					//修改后改变动态数据后更新缓存数据；
					Cache::instance()->set($cache_key,$content);
					echo '<script>alert("保存成功！");window.location.href="/home/extension_json/'.$type.'"</script>';
					exit;
				}
				else
				{
					echo '<script>alert("保存失败！");window.location.href="/home/extension_json/'.$type.'"</script>';
					exit;
				}
			}
		}
		elseif($action_name == 'view')
		{
			//$this->view($desc, $type);
		}
		exit;

	}

	public function action_insert()
	{
	
		$desc	= $this->request->post('fck_html');
		$type	= $this->request->post('position');
		$action_name	= $this->request->post('action_name');

		if(isset($data_counts[$type])) {
			echo '<script>alert("error！");window.location.href="/home/extension_json/'.$type.'"</script>';
			exit;
		}

		if($action_name == 'save')
		{
			if(in_array($type,array_keys(Kohana::config('home.focusposition'))))
			{
				/*
				$content = View::factory('smarty:cooperate/'.$type)
						->set('content', $desc)
						->render();
				if(!Cooperate::valid_content($content,$type))
				{
					echo '<script>alert("内容不符合规定格式，请认真检查！");window.location.href="/home/extension/'.$type.'"</script>';
					exit;
				}
				*/

				$cache_key = Kohana::config('home.cache_key.'.$type);
				if(Home::insert($desc, $type))
				{
					//修改后改变动态数据后更新缓存数据；
					$content = Cooperate::get_content_html($type, $desc);
					Kohana::cache($cache_key,$content);
					Cache::instance()->set($cache_key,$content);
					echo '<script>alert("保存成功！");window.location.href="/home/extension/'.$type.'"</script>';
					exit;
				}
				else
				{
					echo '<script>alert("保存失败！");window.location.href="/home/extension/'.$type.'"</script>';
					exit;
				}
			}
		}
		elseif($action_name == 'view')
		{
			//$this->view($desc, $type);
		}
		exit;
	}

	public function action_add()
	{
	
		$desc	= $this->request->post('fck_html');
		$type	= $this->request->post('position');
	
		$action_name	= $this->request->post('action_name');

		if($action_name == 'save')
		{
			//过滤js
			$regrex	="'<script[^>]*?>.*?</script>'si";

			$desc	= preg_replace($regrex, '', $desc);

			if($this->save($desc, $type))
			{
				if(Kohana::config('home.cache_key.'.$type) != '')
					Kohana::cache(Kohana::config('home.cache_key.'.$type),$desc);
			}
		}
		elseif($action_name == 'view')
		{
			$this->view($desc, $type);
		}

		echo '<script>alert("保存成功！");window.location.href="/home/index/'.$type.'"</script>';
		
		exit;
	}

	private function view($desc, $type)
	{
		$desc	= strval($desc);

		$type	= strval($type);

		$pos_config		= Kohana::config('home.position');

		if(!empty($desc) && in_array($type, $pos_config))
		{
			Home::view_update($desc, $type);		
	
			$domain	= site::domain('member');

			$url	= 'http://'.$domain.'/welcome/index/preview';
			
			$this->request->redirect($url, $code= 302);
		
			exit;
		}

	}

	private function save($desc,$type)
	{
	
		$desc	= strval($desc);

		$type	= strval($type);

		$pos_config		= Kohana::config('home.position');

		if(!empty($desc) && in_array($type, $pos_config))
		{
			Home::update($desc, $type);		
		}

		return true;
	}

}

?>
